package com.qf.shiro;

import com.qf.Dao.UserMapperws;
import com.qf.Dao.UserRepository;

import com.qf.pojo.TbPermissions;

import com.qf.pojo.User;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Created by 54110 on 2021/1/26.
 */
@Component
public class MyRealm extends AuthorizingRealm {


    @Autowired
    UserMapperws userMapperws;
    @Autowired
    UserRepository userRepository;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        String username = (String) principalCollection.getPrimaryPrincipal();
        //5表联查出该用户的权限
        List<TbPermissions> tbPermissionses = userMapperws.findpermissionByUserName(username);
        //进行权限得去重操作
        Set set = new HashSet<>();
        //循环权限List 放置到set中
        for (TbPermissions per : tbPermissionses
        ) {
            set.add(per.getPermissionName());
            System.out.println(per.getPermissionName());
        }

        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        //将去重过去得该用户权限放置在AuthorizationInfo 中
        simpleAuthorizationInfo.addStringPermissions(set);
        return simpleAuthorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String username = (String) authenticationToken.getPrincipal();
        //通过登录名去数据库查询密码
        User byUserName = userRepository.findByName(username);
        System.out.println(byUserName);
        SimpleAuthenticationInfo simpleAuthenticationInfo = null;
        String salt=" peiwanwu";
        if (byUserName != null) {
            simpleAuthenticationInfo = new SimpleAuthenticationInfo(username, byUserName.getPassword(), ByteSource.Util.bytes(salt),getName());
            return simpleAuthenticationInfo;
        } else {
            return simpleAuthenticationInfo;
        }

    }
}
